import pymysql
from flask import Flask,request,jsonify,make_response

app = Flask(__name__)

# 连接数据库
def get_db_connection():
    return pymysql.connect(
        host="localhost",
        user="root",
        password="123456",
        database="rpa",
        charset="utf8mb4"
    )


#查询全部
@app.route('/get_vendors')
def get_vendors():
    connection  = get_db_connection()
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM emp")
        result = cursor.fetchall()
    connection.close()
    return jsonify(result)

@app.route('/get_id/<int:id>')
def get_id(id):
    return jsonify(getId(id))

@app.route('/save',methods=['POST'])
def save():
    data = request.get_json()
    try:
        connection = get_db_connection()
        with connection.cursor() as cursor:
            cursor.execute("INSERT INTO emp (emp_name, emp_age, dept_id) VALUES (%s, %s, %s)",
                           (data['emp_name'], data['emp_age'], data['dept_id']))
        connection.commit()
    except Exception as e:
        return jsonify({"result": "error", "message": str(e)}), 500
    finally:
        connection.close()
    return jsonify({"result": "success"})

@app.route("/delete_id/<int:id>",methods=["DELETE"])
def delete_id(id):
    if getId(id):
        try:
            connection = get_db_connection()
            with connection.cursor() as cursor:
                cursor.execute("DELETE FROM emp WHERE emp_id = %s",(id))
            connection.commit()
        except Exception as e:
            return jsonify({"result": "error", "message": str(e)}), 500
        finally:
            connection.close()
        return jsonify({"result": "success"})
    else:
        return jsonify({"result": "error", "message": "id not found"}), 404






def getId(id):
    connection = get_db_connection()
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM emp WHERE emp_id = %s",(id))
        result = cursor.fetchall()
        connection.close()
        return result

if __name__ == '__main__':
    app.run(port=1212)


